<?php
/**
 * File uploader class
 * @package Upload
 * @author Kirill Egorov
 */
class Upload_File
{
    protected $_config;
    
    public function __construct(array $config){
        $this->_config = $config;
    }
    /**
     * Upload file
     * @param array $data - $_FILES array item
     * @param string $path
     * @return array / false on error
     */
    public function upload(array $data, $path)
	{
	          if($data['error'])
	              return false;

	         $result = array(
	             'name'=>'',
	             'path'=>'',
	             'size'=>'',
	             'type'=>''
	         );
	         
	         $name = str_replace(' ','_' , $data['name']);
	         $name =  preg_replace("/[^A-Za-z0-9_\-\.]/i",'',$name);
	    
	        $ext = File::getExt($name);
	        
	        if(!in_array($ext , $this->_config['extensions'])){  
	            return false;
	        }
	        
	        $namePart = str_replace($ext, '' ,$name);
	        
	        if(file_exists($path.$namePart.$ext)){
	                $namePart.='-0';
	        }
	        
	        while (file_exists($path.$namePart.$ext)){
	                $lastChar = strlen($namePart)-1;
	                $digit = (int) $namePart[$lastChar]; 
	                $namePart[$lastChar] = ++$digit;
	        }
	        
	        $result['name'] = $namePart.$ext;
	        $result['path'] = $path.$namePart.$ext;
	        $result['ext'] = $ext;
	        
			if(!@move_uploaded_file($data['tmp_name'],$result['path'] )){
			    return false;
			}

			$result['size'] = $data['size'];
			$result['type'] = $data['type'];
				
		    @chmod($result['path'],0644);

			return $result;
	}
}